import React, { useState, useRef, useEffect } from 'react'
import './index.less'
import { Icon, Button } from 'react-vant';
import upload from '../../../../../utils/upload'
const Shot = (props) => {
    const videoRef = useRef();
    const canvasRef = useRef();
    const [stream, setstream] = useState();
    const [isShow, setIsShow] = useState(true)
    const [files, setFile] = useState()
    useEffect(() => {
        handlePhoto()
    }, [])
    //判断是否可以使用系统摄像头
    function handlePhoto() {
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            console.log('调用了相机')
            getUserMedia({
                video: {
                    width: 370,
                    height: 667
                }
            }, success, error);
        } else {
            alert('不支持访问用户媒体');
        }
        if (!navigator.mediaDevices) {
            alert("不支持访问用户媒体")
            return
        }
        function error(error) {
            console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
        }
    }
    //调用系统摄像，进行拍照
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints, success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }
    //成功回调
    function success(stream) {
        setstream(stream)
        let video = document.getElementById('video');

        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源

        // video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    }

    //拍照
    function uploadImage() {
        var context = canvasRef.current.getContext('2d');   //canvasRef同videoRef一样也是获取到的canvas元素，其他框架同学获取到的canvas==canvasRef.current;
        canvasRef.current.width = videoRef.current.offsetWidth;
        canvasRef.current.height = videoRef.current.offsetHeight;
        context.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height); //绘制当前画面，形成图片
        videoRef.current.pause(); //暂停摄像头视频流

        stream.getTracks()[0].stop();
        setIsShow(false)
        var imgURL = canvasRef.current.toDataURL('image/jpeg', 60 / 100); //获取到的图片，这里的图片是base64位的，只需要base64图片的同学到这里就可以停止了
        //这里可以执行你的上传方法（$files ）
        var files = dataURLtoFile(imgURL)   //将base64转换为blob,需要file进行上传
        setFile(files)
    }
    //向后台发送图片
    const sendImg = async () => {
        //调用上传图片方法
        upload(files, props)

        //异步方法（解决实时更新问题）
        setTimeout(() => {
            props.getMessageList()
        }, 100)
        //关闭
        props.changeShot()
    }
    //把拍摄到的图片转为blob
    function dataURLtoFile(dataurl, filename = 'file') {
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let suffix = mime.split('/')[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        console.log(u8arr, 'zxcvbnm');
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, { type: mime })
    }
    //关闭摄像头
    const cancelShot = (e) => {
        stream.getTracks()[0].stop();
        props.changeShot();
        //阻止冒泡事件
        e.preventDefault()  
    }
    return (
        <div className="shotBox">
            <video id="video" ref={videoRef} autoPlay style={{ width: "100%", height: "100%", objectFit: "fill" }}></video>
            {
                isShow ? <div className="btn">
                    <div className="closephoto" onTouchEnd={(e) => {cancelShot(e)}}>
                        <Icon name="arrow-down" />
                    </div>
                    <div onTouchEnd={uploadImage} className="capture">
                        <div></div>
                    </div>
                </div > : <div onTouchEnd={() => {
                    sendImg()
                }} className="closecanvas" >
                        <p onClick={() => {
                            console.log(398476);
                        }}>
                            <Icon name="revoke" />
                        </p>
                        <Button className="but" size="small" color="#05c160">发送</Button>
                    </div>
            }
            <canvas ref={canvasRef} className="canvas"></canvas>
        </div >
    )
}
export default Shot
